#include <fstream>

#include "wave_reader.h"
#include "wave_writer.h"

WaveWriter::WaveWriterPtr WaveWriter::ins;

bool WaveWriter::SaveWave(const std::string &wavePath)
{
  WaveReader::WaveReaderPtr wave_r = WaveReader::GetInstance();
  data.id = MAKEFOURCC('d', 'a', 't', 'a');
  data.size = buffer.size() * 2/*wave_r->GetDataSize()*/;
  data.data = new char[data.size];
  char *tmp = (char*)ListToshortArray(buffer);
  memcpy(data.data, tmp, data.size);
  delete[] tmp;

  std::ofstream dest;
  dest.open(wavePath.c_str(), std::ios::out | std::ios::binary);

  dest.write((char*)&riff.id, sizeof(DWORD));
  dest.write((char*)&riff.size, sizeof(long));
  dest.write((char*)&wave.wave_id, sizeof(DWORD));
  dest.write((char*)&wave.fmt_id, sizeof(DWORD));
  dest.write((char*)&wave.size, sizeof(long));
  dest.write((char*)&wave.desc, wave.size);
  dest.write((char*)&data.id, sizeof(DWORD));
  dest.write((char*)&data.size, sizeof(long));
  dest.write(data.data, data.size);

  dest.close();

  return true;
}

short *WaveWriter::ListToshortArray(const std::vector<short> &ls)
{
  short *arr = new short[ls.size()];

  int i = 0;
  for each (short w in ls)
  {
    arr[i++] = w;
  }

  return arr;
}